import 'package:flutter/material.dart';

void main() {
  runApp(const DartControlFlowApp());
}

class DartControlFlowApp extends StatelessWidget {
  const DartControlFlowApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Dart 控制流演示',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: const ControlFlowDemoScreen(),
    );
  }
}

class ControlFlowDemoScreen extends StatefulWidget {
  const ControlFlowDemoScreen({super.key});

  @override
  State<ControlFlowDemoScreen> createState() => _ControlFlowDemoScreenState();
}

class _ControlFlowDemoScreenState extends State<ControlFlowDemoScreen> {
  String _output = '';
  bool _isLoading = false;
  final ScrollController _scrollController = ScrollController();

  // 分支语句演示
  void _runBranchDemo() {
    _clearOutput();
    _log("\n=== 分支语句演示 ===");
    int age = 18;
    bool isStudent = true;

    // if 语句
    if (age >= 18) {
      _log("成年人");
      if (isStudent) {
        _log("但还是学生");
      }
    } else {
      _log("未成年人");
    }

    // if-else if-else 链
    String grade = "B";
    if (grade == "A") {
      _log("优秀");
    } else if (grade == "B") {
      _log("良好"); // 输出
    } else {
      _log("一般");
    }

    // 条件表达式（三元运算符）
    String message = age >= 18 ? "可以投票" : "不能投票";
    _log("三元运算符: $message");

    // 级联条件（&& 和 ||）
    if (age >= 18 && !isStudent) {
      _log("成年人且非学生");
    } else if (age < 18 || isStudent) {
      _log("未成年人或学生");
    }

    // switch-case
    int day = 3;
    switch (day) {
      case 1:
        _log("周一");
        break;
      case 2:
        _log("周二");
        break;
      case 3:
        _log("周三"); // 输出
        break;
      default:
        _log("其他日期");
    }
  }

  // 循环语句演示
  void _runLoopDemo() async {
    _clearOutput();
    _log("\n=== 循环语句演示 ===");
    List<String> fruits = ["苹果", "香蕉", "橙子"];
    Map<String, int> scores = {"Alice": 90, "Bob": 85, "Charlie": 95};

    // for 循环（索引遍历）
    _log("\nfor 循环（索引）:");
    for (int i = 0; i < fruits.length; i++) {
      _log("索引 $i: ${fruits[i]}");
      await Future.delayed(const Duration(milliseconds: 300));
    }

    // for-in 循环（集合遍历）
    _log("\nfor-in 循环（集合）:");
    for (String fruit in fruits) {
      _log(fruit);
      await Future.delayed(const Duration(milliseconds: 300));
    }

    // forEach 方法
    _log("\nforEach 循环:");
    fruits.forEach((fruit) => _log(fruit));

    // while 循环
    _log("\nwhile 循环:");
    int count = 0;
    while (count < 3) {
      _log("Count: $count");
      count++;
      await Future.delayed(const Duration(milliseconds: 500));
    }

    // do-while 循环
    _log("\ndo-while 循环:");
    int retry = 0;
    do {
      _log("重试次数: $retry");
      retry++;
      await Future.delayed(const Duration(milliseconds: 500));
    } while (retry < 2);

    // break 和 continue
    _log("\nbreak 和 continue 演示:");
    for (int i = 0; i < 5; i++) {
      if (i == 2) {
        _log("跳过 i=2");
        continue;
      }
      if (i == 4) {
        _log("终止循环 at i=4");
        break;
      }
      _log("i: $i");
      await Future.delayed(const Duration(milliseconds: 500));
    }

    // 遍历 Map
    _log("\n遍历 Map:");
    scores.forEach((name, score) {
      _log("$name: $score 分");
    });
  }

  // 运行所有演示
  void _runAllDemos() async {
    setState(() {
      _isLoading = true;
      _output = '正在运行所有演示...\n';
    });

    await Future.delayed(const Duration(milliseconds: 500));

    _runBranchDemo();
    await Future.delayed(const Duration(seconds: 1));

    _runLoopDemo();

    setState(() {
      _isLoading = false;
    });
  }

  // 辅助方法
  void _log(String message) {
    setState(() {
      _output += '$message\n';
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    });
  }

  void _clearOutput() {
    setState(() {
      _output = '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Dart 控制流演示'), centerTitle: true),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 控制按钮
            Wrap(
              spacing: 8.0,
              runSpacing: 8.0,
              children: [
                ElevatedButton(
                  onPressed: _runBranchDemo,
                  child: const Text('分支语句'),
                ),
                ElevatedButton(
                  onPressed: _runLoopDemo,
                  child: const Text('循环语句'),
                ),
                ElevatedButton(
                  onPressed: _runAllDemos,
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.green,
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      if (_isLoading)
                        const SizedBox(
                          width: 16,
                          height: 16,
                          child: CircularProgressIndicator(
                            color: Colors.white,
                            strokeWidth: 2,
                          ),
                        ),
                      if (_isLoading) const SizedBox(width: 8),
                      const Text('运行全部'),
                    ],
                  ),
                ),
              ],
            ),

            const SizedBox(height: 16),

            // 输出区域
            Expanded(
              child: Container(
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.grey.shade300),
                  borderRadius: BorderRadius.circular(8),
                  color: Colors.grey.shade50,
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    Container(
                      padding: const EdgeInsets.all(8),
                      color: Colors.grey.shade200,
                      child: const Text(
                        '输出结果',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                    ),
                    Expanded(
                      child: SingleChildScrollView(
                        controller: _scrollController,
                        padding: const EdgeInsets.all(12),
                        child: SelectableText(
                          _output.isEmpty ? '点击上方按钮运行演示...' : _output,
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 14,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
